<template>
  <div class="app-container">
    <!-- 练习进度信息 -->
    <el-card class="progress-container" shadow="never" style="margin-bottom: 20px;">
      <div class="progress-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="progress-item">
              <div class="progress-label">当前题目</div>
              <div class="progress-value">{{ currentQuestionIndex + 1 }} / {{ initialTotalQuestions || totalQuestions }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="progress-item">
              <div class="progress-label">正确次数</div>
              <div class="progress-value">{{ correctCount }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="progress-item">
              <div class="progress-label">练习模式</div>
              <div class="progress-value">{{ orderType === 0 ? '顺序练习' : '乱序练习' }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 题目内容 -->
    <el-card v-if="quData && quData.id" class="question-container" shadow="never">
      <div class="question-content">
        <div class="question-header">
          <span class="question-type">【{{ quData.quType | quTypeFilter }}】</span>
          <span class="question-title">{{ quData.content }}</span>
        </div>
        
        <div v-if="quData.image && quData.image !== ''" class="question-image">
          <el-image :src="quData.image" style="max-width: 100%;" />
        </div>

        <!-- 单选题和判断题 -->
        <div v-if="quData.quType === 1 || quData.quType === 3" class="answer-section">
          <el-radio-group v-model="answerValues[0]" @change="handleRadioChange" :disabled="showAnalysis">
            <el-radio v-for="(an, index) in quData.answerList" :key="an.id" :label="an.id" class="answer-option" :class="{ 'locked': showAnalysis }">
              <span class="option-label">{{ an.abc }}.</span>
              <span class="option-content">{{ an.content }}</span>
              <div v-if="an.image && an.image !== ''" class="option-image">
                <el-image :src="an.image" style="max-width: 100%;" />
              </div>
            </el-radio>
          </el-radio-group>
        </div>

        <!-- 多选题 -->
        <div v-if="quData.quType === 2" class="answer-section">
          <el-checkbox-group v-model="answerValues" @change="handleCheckboxChange" :disabled="showAnalysis">
            <el-checkbox v-for="(an, index) in quData.answerList" :key="an.id" :label="an.id" class="answer-option" :class="{ 'locked': showAnalysis }">
              <span class="option-label">{{ an.abc }}.</span>
              <span class="option-content">{{ an.content }}</span>
              <div v-if="an.image && an.image !== ''" class="option-image">
                <el-image :src="an.image" style="max-width: 100%;" />
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 答案解析 -->
        <div v-if="showAnalysis" class="analysis-section">
          <div class="analysis-header">
            <span class="analysis-title">答案解析</span>
            <span class="analysis-result" :class="isCorrect ? 'correct' : 'incorrect'">
              {{ isCorrect ? '回答正确' : '回答错误' }}
            </span>
          </div>
          
          <div class="lock-notice">
            <i class="el-icon-lock"></i>
            <span>选项已锁定，无法再次修改</span>
          </div>
          
          <div v-if="isCorrect" class="progress-notice">
            <i class="el-icon-success"></i>
            <span>回答正确！当正确次数大于错误次数时，该题目将自动转为历史错题。</span>
          </div>
          
          <div class="analysis-content">
            <p><strong>正确答案：</strong>{{ rightTags.join(' ') }}</p>
            <p v-if="quData.analysis"><strong>题目解析：</strong>{{ quData.analysis }}</p>
            
            <!-- 选项解析 -->
            <div v-if="hasOptionAnalysis" class="option-analysis">
              <p><strong>选项解析：</strong></p>
              <div v-for="an in quData.answerList" v-if="an.analysis" :key="an.id" class="option-analysis-item">
                <span class="option-tag">{{ an.abc }}.</span>
                <span class="option-text">{{ an.content }}：</span>
                <span class="option-analysis">{{ an.analysis }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button v-if="!showAnalysis" type="primary" @click="submitAnswer" :disabled="!hasAnswer">
        提交答案
      </el-button>
      <el-button v-if="showAnalysis" type="success" @click="nextQuestion">
        {{ hasNextQuestion ? '下一题' : '完成练习' }}
      </el-button>
      <el-button @click="exitPractice">退出练习</el-button>
    </div>

    <!-- 练习完成对话框 -->
    <el-dialog title="练习完成" :visible.sync="finishDialogVisible" width="500px">
      <div class="finish-content">
        <div class="finish-stats">
          <div class="finish-stat-item">
            <div class="finish-stat-value">{{ initialTotalQuestions || totalQuestions }}</div>
            <div class="finish-stat-label">总题数</div>
          </div>
          <div class="finish-stat-item">
            <div class="finish-stat-value">{{ correctCount }}</div>
            <div class="finish-stat-label">正确题数</div>
          </div>
          <div class="finish-stat-item">
            <div class="finish-stat-value">{{ accuracy }}%</div>
            <div class="finish-stat-label">正确率</div>
          </div>
        </div>
        <div class="finish-message">
          <p v-if="movedToHistoryCount > 0">
            🎉 恭喜！有 {{ movedToHistoryCount }} 道题目已转为历史错题，说明您已经掌握了这些知识点。
          </p>
          <p v-else-if="correctCount > 0">
            ✅ 本次练习中您答对了 {{ correctCount }} 道题目，继续努力，当正确次数大于错误次数时，这些题目将自动转为历史错题。
          </p>
          <p>💪 继续加油，相信您会越来越棒的！</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closePractice">关闭</el-button>
        <el-button @click="restartPractice" :loading="restarting">重新练习</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchDetail } from '@/api/qu/qu'
import { getNextPracticeQu, submitPracticeAnswer, getPracticeStats, startPractice } from '@/api/user/book'
import { post } from '@/utils/request'

export default {
  name: 'BookPractice',
  filters: {
    quTypeFilter(quType) {
      const quTypes = { 1: '单选题', 2: '多选题', 3: '判断题' }
      return quTypes[quType] || '未知题型'
    }
  },
  data() {
    return {
      quId: '',
      orderType: 0,
      quData: {},
      answerValues: [],
      rightValues: [],
      rightTags: [],
      showAnalysis: false,
      isCorrect: false,
      hasAnswer: false,
      currentQuestionIndex: 0,
      totalQuestions: 0,
      correctCount: 0,
      movedToHistoryCount: 0,
      finishDialogVisible: false,
      hasNextQuestion: true,
      practiceStats: null,
      initialTotalQuestions: 0, // 练习开始时的总题数
      restarting: false, // 重新练习加载状态
      tags: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
    }
  },
  computed: {
    accuracy() {
      const totalQuestions = this.initialTotalQuestions || this.totalQuestions
      return totalQuestions > 0 ? Math.round((this.correctCount / totalQuestions) * 100) : 0
    },
    hasOptionAnalysis() {
      return this.quData.answerList && this.quData.answerList.some(an => an.analysis)
    }
  },
  created() {
    this.quId = this.$route.params.quId
    this.orderType = parseInt(this.$route.query.orderType) || 0
    this.loadPracticeStats()
    this.loadQuestion()
  },
  methods: {
    loadPracticeStats() {
      // 加载练习统计信息
      getPracticeStats({ examId: 'default' }).then(response => {
        console.log('练习统计响应:', response)
        if (response && response.code === 0) {
          this.practiceStats = response.data
          this.totalQuestions = response.data.currentCount || 0
          // 如果是第一次加载，保存初始总题数
          if (this.initialTotalQuestions === 0) {
            this.initialTotalQuestions = response.data.currentCount || 0
          }
          console.log('练习统计数据:', response.data)
        } else {
          console.error('练习统计响应错误:', response)
        }
      }).catch(error => {
        console.error('加载练习统计失败:', error)
        // 如果统计加载失败，尝试从错题列表获取数量
        this.loadQuestionCountFromList()
      })
    },
    
    loadQuestionCountFromList() {
      // 从错题列表获取数量作为备用方案
      post('/exam/api/user/wrong-book/paging', {
        current: 1,
        size: 1,
        params: {}
      }).then(response => {
        if (response && response.code === 0 && response.data) {
          this.totalQuestions = response.data.total || 0
          this.practiceStats = {
            currentCount: response.data.total || 0,
            historyCount: 0,
            totalCorrectCount: 0,
            accuracy: 0
          }
        }
      }).catch(error => {
        console.error('从列表获取错题数量失败:', error)
      })
    },
    
    loadQuestion() {
      if (!this.quId) {
        this.$message.error('题目ID不存在')
        this.$router.push('/wrong-book/index')
        return
      }
      
      this.clearAnswer()
      console.log('加载题目ID:', this.quId)
      
      fetchDetail(this.quId).then(response => {
        console.log('题目详情响应:', response)
        if (response && response.data) {
          this.quData = response.data
          
          // 处理答案选项
          if (this.quData.answerList && this.quData.answerList.length > 0) {
            this.quData.answerList.forEach((an, index) => {
              an.abc = this.tags[index]
              if (an.isRight) {
                this.rightValues.push(an.id)
                this.rightTags.push(an.abc)
              }
            })
          } else {
            console.warn('题目没有答案选项')
          }
        } else {
          console.error('题目数据为空')
          this.$message.error('题目数据为空')
        }
      }).catch(error => {
        console.error('加载题目失败:', error)
        this.$message.error('加载题目失败: ' + (error.message || '请稍后重试'))
        
        // 如果题目加载失败，尝试返回错题集列表
        setTimeout(() => {
          this.$router.push('/wrong-book/index')
        }, 2000)
      })
    },
    
    clearAnswer() {
      this.answerValues = []
      this.rightValues = []
      this.rightTags = []
      this.showAnalysis = false
      this.hasAnswer = false
      this.isCorrect = false
    },
    
    handleRadioChange(value) {
      this.answerValues = [value]
      this.hasAnswer = true
    },
    
    handleCheckboxChange(value) {
      this.answerValues = value
      this.hasAnswer = value.length > 0
    },
    
    submitAnswer() {
      if (!this.hasAnswer) {
        this.$message.warning('请先选择答案')
        return
      }
      
      // 判断答案是否正确
      let isCorrect = false
      if (this.quData.quType === 1 || this.quData.quType === 3) {
        // 单选题或判断题
        isCorrect = this.rightValues.join(',') === this.answerValues[0]
      } else if (this.quData.quType === 2) {
        // 多选题
        const userAnswers = [...this.answerValues].sort()
        const correctAnswers = [...this.rightValues].sort()
        isCorrect = userAnswers.join(',') === correctAnswers.join(',')
      }
      
      this.isCorrect = isCorrect
      this.showAnalysis = true
      
      // 立即锁定选项，防止用户再次修改
      this.hasAnswer = false
      
      // 提交答案到后端
      submitPracticeAnswer({
        examId: 'default',
        quId: this.quId,
        isCorrect: isCorrect
      }).then(response => {
        console.log('提交答案响应:', response)
        if (response && response.code === 0) {
          const movedToHistory = response.data
          console.log('是否转为历史错题:', movedToHistory)
          console.log('当前题目信息:', {
            quId: this.quId,
            isCorrect: isCorrect,
            movedToHistory: movedToHistory
          })
          
          if (movedToHistory) {
            this.movedToHistoryCount++
            this.$message({
              type: 'success',
              message: '🎉 恭喜！这道题目已转为历史错题，说明您已经掌握了这个知识点！',
              duration: 3000
            })
          } else if (isCorrect) {
            // 回答正确但还未转为历史错题
            this.$message({
              type: 'info',
              message: '✅ 回答正确！继续努力，当正确次数大于错误次数时，该题目将转为历史错题。',
              duration: 2000
            })
          }
        }
      }).catch(error => {
        console.error('提交答案失败:', error)
        this.$message.error('提交答案失败，请稍后重试')
      })
      
      // 更新统计
      if (isCorrect) {
        this.correctCount++
      }
    },
    
    nextQuestion() {
      if (!this.hasNextQuestion) {
        this.finishDialogVisible = true
        return
      }
      
      // 获取下一题
      getNextPracticeQu({
        examId: 'default',
        quId: this.quId,
        orderType: this.orderType
      }).then(response => {
        if (response && response.code === 0 && response.data && response.data.id) {
          this.quId = response.data.id
          this.currentQuestionIndex++
          this.loadQuestion()
        } else {
          // 如果没有下一题，检查是否还有更多错题可以练习
          this.checkForMoreQuestions()
        }
      }).catch(error => {
        console.error('获取下一题失败:', error)
        this.$message.error('获取下一题失败，请稍后重试')
      })
    },
    
    checkForMoreQuestions() {
      // 检查是否已完成所有初始题目
      const totalQuestions = this.initialTotalQuestions || this.totalQuestions
      if (this.currentQuestionIndex + 1 >= totalQuestions) {
        // 已完成所有初始题目
        this.hasNextQuestion = false
        this.finishDialogVisible = true
      } else {
        // 重新获取练习统计，检查是否还有更多错题
        getPracticeStats({ examId: 'default' }).then(response => {
          if (response && response.code === 0 && response.data) {
            const stats = response.data
            if (stats.currentCount > 0) {
              // 如果还有当前错题，重新开始练习
              this.$message.info('还有更多错题可以练习，重新开始练习')
              this.restartPractice()
            } else {
              // 真的没有更多错题了
              this.hasNextQuestion = false
              this.finishDialogVisible = true
            }
          } else {
            this.hasNextQuestion = false
            this.finishDialogVisible = true
          }
        }).catch(error => {
          console.error('检查错题数量失败:', error)
          this.hasNextQuestion = false
          this.finishDialogVisible = true
        })
      }
    },
    
    exitPractice() {
      this.$confirm('确定要退出练习吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/wrong-book/index')
      })
    },
    
    closePractice() {
      // 关闭练习对话框并返回错题集页面
      this.finishDialogVisible = false
      // 通知错题集页面刷新数据
      this.$router.push('/wrong-book/index')
      // 使用事件总线通知父页面刷新
      this.$nextTick(() => {
        this.$bus && this.$bus.$emit('refreshPracticeStats')
      })
    },
    
    restartPractice() {
      console.log('重新练习按钮被点击')
      this.restarting = true
      // 重新开始练习
      startPractice({
        examId: 'default',
        orderType: this.orderType
      }).then(response => {
        console.log('重新练习响应:', response)
        if (response && response.code === 0 && response.data && response.data.id) {
          this.quId = response.data.id
          this.currentQuestionIndex = 0
          this.correctCount = 0
          this.movedToHistoryCount = 0
          this.hasNextQuestion = true
          this.initialTotalQuestions = 0 // 重置初始总题数
          this.finishDialogVisible = false // 成功开始新一轮练习后关闭对话框
          this.loadPracticeStats()
          this.loadQuestion()
        } else {
          this.$message.warning('没有可练习的错题')
          this.$router.push('/wrong-book/index')
        }
        this.restarting = false
      }).catch(error => {
        console.error('重新开始练习失败:', error)
        this.$message.error('重新开始练习失败，请稍后重试')
        this.$router.push('/wrong-book/index')
        this.restarting = false
      })
    }
  }
}
</script>

<style scoped>
.progress-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.progress-content {
  padding: 15px 0;
}

.progress-item {
  text-align: center;
}

.progress-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 5px;
}

.progress-value {
  font-size: 18px;
  font-weight: bold;
}

.question-container {
  margin-bottom: 20px;
}

.question-content {
  padding: 20px;
}

.question-header {
  margin-bottom: 20px;
}

.question-type {
  color: #409EFF;
  font-weight: bold;
  margin-right: 10px;
}

.question-title {
  font-size: 16px;
  line-height: 1.6;
}

.question-image {
  margin: 20px 0;
  text-align: center;
}

.answer-section {
  margin: 20px 0;
}

.answer-option {
  display: block;
  margin: 15px 0;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  transition: all 0.3s;
}

.answer-option:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.answer-option.locked {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  cursor: not-allowed;
  opacity: 0.8;
}

.answer-option.locked:hover {
  border-color: #e4e7ed;
  background-color: #f5f7fa;
}

.option-label {
  font-weight: bold;
  margin-right: 8px;
}

.option-content {
  line-height: 1.5;
}

.option-image {
  margin-top: 10px;
}

.analysis-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.analysis-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.analysis-result {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: bold;
}

.analysis-result.correct {
  background-color: #f0f9ff;
  color: #67c23a;
}

.analysis-result.incorrect {
  background-color: #fef0f0;
  color: #f56c6c;
}

.lock-notice {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  color: #409EFF;
  font-size: 14px;
}

.lock-notice i {
  margin-right: 6px;
  font-size: 16px;
}

.progress-notice {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
  border-radius: 4px;
  color: #67c23a;
  font-size: 14px;
}

.progress-notice i {
  margin-right: 6px;
  font-size: 16px;
}

.analysis-content p {
  margin: 10px 0;
  line-height: 1.6;
}

.option-analysis {
  margin-top: 15px;
}

.option-analysis-item {
  margin: 10px 0;
  padding: 8px;
  background-color: white;
  border-radius: 4px;
}

.option-tag {
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
}

.option-text {
  color: #666;
}

.option-analysis {
  color: #333;
}

.action-buttons {
  text-align: center;
  padding: 20px 0;
}

.action-buttons .el-button {
  margin: 0 10px;
  padding: 12px 24px;
}

.finish-content {
  text-align: center;
}

.finish-stats {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.finish-stat-item {
  text-align: center;
}

.finish-stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.finish-stat-label {
  font-size: 14px;
  color: #666;
}

.finish-message {
  margin-top: 20px;
  color: #666;
  line-height: 1.6;
}

.finish-message p {
  margin: 10px 0;
}
</style>
